import socket
import time
import numpy as np
import cv2
from cv2 import data
from numpy.lib.type_check import imag
# text_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# text_sock.bind((self_ip, text_port))
IP = '114.212.84.31'
PORT = 42000

PIC_DIR = 'E:\\Unity-workspace\\MyCar\\png\\'
 
def pic_load(pic_dir,pic_id:int):
    pic_name = pic_dir+"camera_{}.png".format(pic_id)
    img = cv2.imread(pic_name)
    # cv2.imshow("Client Test", img)
    # time.sleep(1)
    return img

def send_pic(conn : socket.socket, img):
    ret, img_encode = cv2.imencode('.png',img)

    data_encode = np.array(img_encode)
    data = data_encode.tostring()

    pic_sz = str.encode(str(len(data)).ljust(16))
    conn.send(pic_sz)

    answer = conn.recv(1024).decode("utf-8")
    if answer == 'Get':
        conn.send(data)


def main():
    camera_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    camera_client.connect((IP, PORT))
    print('[+] Unity端连接成功')

    while True:
        msg = input('>>>')
        if msg == 'quit':
            break
        if len(msg) == 0:
            continue

        try:
            id = int(msg)
            img = pic_load(PIC_DIR,id)
            send_pic(camera_client,img)
            # data = camera_client.recv(1024).decode('utf-8')
        except ConnectionResetError:
            print('远程主机已关闭')
            break

        # if not data:
        #     print('[+]  Server主动断开链接.....')
        #     break
        # else:
        #     print("[localtime] {0} \t  服务器端消息：{1}".format(
        #             time.asctime(time.localtime()), data))


    print("[+] Client端关闭")
    camera_client.close()

if __name__ == '__main__':
    main()